#include "lscan.h"
#include "ui_lscan.h"

lscan::lscan(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::lscan)
{
    ui->setupUi(this);
    ui->lineEdit->setText("12.0.0.0/24");
    myProcess = new QProcess(this);
    connect(myProcess,&QProcess::readyReadStandardOutput,this,&lscan::readyRead);
    connect(myProcess,&QProcess::readyReadStandardError,this,&lscan::readyError);
    connect(myProcess,&QProcess::finished,this,&lscan::finished);
    model = new QStandardItemModel;
    // 添加标题
    model->setHorizontalHeaderLabels(QStringList() << "ip"<<"MAC地址"<<"状态"<<"位置");
    ui->tableView->setModel(model);
    //ui->tableView->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    this->readInfoFile(&lhash);
}

lscan::~lscan()
{
    delete ui;
}

//导出qtableview数据到字符串
QString lscan::dump_tableview(QStandardItemModel *m){
    int rowCount = m->rowCount();
    int columnCount = m->columnCount();
    QString textContent;
    for (int row = 0; row < rowCount; ++row) {
        for (int column = 0; column < columnCount; ++column) {
            QModelIndex index = m->index(row, column);
            QString data = m->data(index).toString();
            textContent += data;
            if (column < columnCount - 1) {
                textContent += "\t";
            }
        }
        textContent += "\n";
    }
    return textContent;
}

void lscan::readInfoFile(QHash<QString, QString> *hash){
    hash->clear();
    QFile file(infoName);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            in.setEncoding(QStringConverter::Utf8);

            while (!in.atEnd()) {
                QString line = in.readLine().trimmed();
                QStringList parts = line.split('\t');
                if (parts.size() >= 2) {
                    hash->insert(parts[0], parts[parts.size()-1]);
                }
            }
            file.close();
        } else {
            qDebug() << "无法打开文件。" ;
        }

}
void lscan::on_pushButton_clicked()
{
    this->readInfoFile(&lhash);
    model->clear();
    table_row = -1;
    // 添加标题
    model->setHorizontalHeaderLabels(QStringList() << "ip"<<"MAC地址"<<"状态"<<"位置");
    // 设置要执行的命令和参数
    QString program = "sudo";
    QStringList arguments;
    //arguments<<"ls";
    arguments<<"nmap"<< "-sn"<< ui->lineEdit->text();

    myProcess->start(program, arguments);
    ui->pushButton->setDisabled(true);

}

void lscan::readyRead(){
    QByteArray output = myProcess->readAllStandardOutput();
    QString str = QString::fromUtf8(output);
    QStringList scanstr = str.split("\n");
    //创建一个 QStandardItem 并设置其数据

    for (const QString &line : scanstr) {
        //qDebug() << line;
        if(line.contains("Nmap")){
            QRegularExpression ipRegex("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b");
            QRegularExpressionMatch match = ipRegex.match(line);
            if (match.hasMatch()) {
                QString ip = match.captured(0);
                table_row++;
                QStandardItem *item_ip = new QStandardItem(ip);
                QStandardItem *site = new QStandardItem(lhash.value(ip));
                //将项添加到模型的第 1 行第 1 列（索引从 0 开始）
                model->setItem(table_row, 0, item_ip);
                model->setItem(table_row, 3, site);
            } else {
                continue;
            }
        }
        if(line.contains("MAC")){
            QRegularExpression re("([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5})");
            QRegularExpressionMatch matchmac = re.match(line);
            //qDebug()<<"mac:"<<matchmac.captured(0);
            if (matchmac.hasMatch()) {
                QStandardItem *item_mac = new QStandardItem(matchmac.captured(0));
                model->setItem(table_row,1,item_mac);
            }
        }

        if(line.contains("Host")){
            QString hostStat = "离线";
            if(line.contains("Host is up")){
                hostStat = "在线";
            }
            QStandardItem *item_status = new QStandardItem(hostStat);
            model->setItem(table_row,2,item_status);
        }
    }

    //model->setRowCount(10);
}

void lscan::readyError(){
    QByteArray output = myProcess->readAllStandardError();
}

void lscan::finished(int exitCode, QProcess::ExitStatus exitStatus){
    ui->pushButton->setEnabled(true);
}

void lscan::on_pushButton_2_clicked()
{
    //qDebug()<<"tableview:"<<this->dump_tableview(model);
    QString fileName = QFileDialog::getSaveFileName(this, "保存文件", "", "文本文件 (*.txt)");
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << this->dump_tableview(model);
            file.close();
        }
    }
}


void lscan::on_pushButton_3_clicked()
{
    QString fileName = infoName;
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << this->dump_tableview(model);
            file.close();
            QMessageBox::about(this,"保存","成功!");
        }
    }
}

